package com.qiwenshare.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.qiwenshare.common.cbb.DateUtil;
import com.qiwenshare.common.util.PathUtil;
import com.qiwenshare.common.cbb.RestResult;
import com.qiwenshare.common.operation.FileOperation;
import com.qiwenshare.web.anno.MyLog;
import com.qiwenshare.web.api.IAlbumService;
import com.qiwenshare.web.api.IFileService;
import com.qiwenshare.web.api.IFiletransferService;
import com.qiwenshare.web.api.IOperationLogService;
import com.qiwenshare.web.cbb.OperationLogUtil;

import com.qiwenshare.web.domain.AlbumBean;
import com.qiwenshare.web.domain.FileBean;
import com.qiwenshare.web.domain.StorageBean;
import com.qiwenshare.web.domain.UserBean;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;

import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/album")
public class AlbumController {
    /**
     * 当前模块
     */
    public static final String CURRENT_MODULE = "相册管理";
    @Resource
    IAlbumService albumService;
    @Resource
    IFileService fileService;
    @Resource
    IFiletransferService filetransferService;
    @Resource
    IOperationLogService operationLogService;

    /**
     * @return
     */
    @RequestMapping(value = "/albumindex")
    @ResponseBody
    public ModelAndView essayIndex() {
        ModelAndView mv = new ModelAndView("/album/albumIndex.html");
        return mv;
    }

    /**
     * 添加相册
     *
     * @param albumBean
     * @return
     */
    @RequestMapping(value = "/addalbum", method = RequestMethod.POST)
    @ResponseBody
    @MyLog(operation = "添加相册", module = CURRENT_MODULE)
    public String addAlbum(HttpServletRequest request, AlbumBean albumBean) {
        RestResult<String> restResult = new RestResult<String>();
        UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();

        if (sessionUserBean == null) {
            restResult.setSuccess(false);
            restResult.setErrorMessage("用户没有登录");
            return JSON.toJSONString(restResult);
        }
        albumBean.setUserid(sessionUserBean.getUserId());

        int albumid = albumService.insertAlbum(albumBean);

        FileBean fileBean = new FileBean();
        fileBean.setFilename(albumBean.getAlbumname());
        fileBean.setUploadtime(DateUtil.getCurrentTime());

        fileBean.setFilepath("/我的相册/");
        fileBean.setIsdir(1);
        fileBean.setUserid(sessionUserBean.getUserId());
        fileBean.setAlbumid(albumBean.getAlbumid());
        fileService.insertFile(fileBean);

        restResult.setSuccess(true);
        restResult.setData("创建成功");
        operationLogService.insertOperationLog(
                OperationLogUtil.getOperationLogObj(request, "成功", CURRENT_MODULE, "创建相册", "创建相册成功"));
        return JSON.toJSONString(restResult);
    }

    /**
     * 删除相册
     *
     * @param albumBean
     * @return
     */
    @RequestMapping(value = "/deletealbum", method = RequestMethod.POST)
    @ResponseBody
    @MyLog(operation = "删除相册", module = CURRENT_MODULE)
    public String deleteAlbum(HttpServletRequest request, AlbumBean albumBean) {
        RestResult<String> restResult = new RestResult<String>();
        albumService.deleteAlbum(albumBean);
        UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
        long sessionUserId = sessionUserBean.getUserId();
        List<FileBean> fileList = fileService.selectFileByAlbumId(albumBean);
        //List<ImageBean> imageList = filetransferService.selectImageByAlbumId(albumBean);
        filetransferService.deleteImageByAlbum(albumBean);
        int deleteFileCount = 0;
        long totalFileSize = 0;
        for (int i = 0; i < fileList.size(); i++) {
            String imageUrl = PathUtil.getStaticPath() + fileList.get(i).getFileurl();
            String minImageUrl = imageUrl.replace("." + fileList.get(i).getExtendname(), "_min." + fileList.get(i).getExtendname());
            totalFileSize += FileOperation.getFileSize(imageUrl);
            FileOperation.deleteFile(imageUrl);
            FileOperation.deleteFile(minImageUrl);
        }
        FileBean fileBean = fileService.selectDirFileByAlbumid(albumBean);

        fileService.deleteFile(fileBean);

        StorageBean storageBean = filetransferService.selectStorageBean(new StorageBean(sessionUserId));
        if (storageBean != null) {
            long updateFileSize = storageBean.getStoragesize() - totalFileSize;
            if (updateFileSize < 0) {
                updateFileSize = 0;
            }
            storageBean.setStoragesize(updateFileSize);
            filetransferService.updateStorageBean(storageBean);

        }
        restResult.setSuccess(true);
        restResult.setData("删除相册部分成功");

        if (deleteFileCount == fileList.size()) {
            restResult.setData("删除相册成功");
        }

        return JSON.toJSONString(restResult);
    }

    /**
     * 修改相册
     *
     * @param albumBean
     * @return
     */
    @RequestMapping(value = "/updatealbum", method = RequestMethod.POST)
    @ResponseBody
    @MyLog(operation = "修改相册", module = CURRENT_MODULE)
    public String updateAlbum(HttpServletRequest request, AlbumBean albumBean) {
        RestResult<String> restResult = new RestResult<String>();
        UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();

//        FileBean fileBean = new FileBean();
//
//        fileBean.setAlbumid(albumBean.getAlbumid());
        FileBean fileBean = fileService.selectDirFileByAlbumid(albumBean);

        if (fileBean == null) {
            fileBean = new FileBean();
            fileBean.setAlbumid(albumBean.getAlbumid());
            fileBean.setFilename(albumBean.getAlbumname());
            fileBean.setUploadtime(DateUtil.getCurrentTime());

            fileBean.setFilepath("/我的相册/" + albumBean.getAlbumname() + "/");
            fileBean.setIsdir(1);
            fileBean.setUserid(sessionUserBean.getUserId());
            fileService.insertFile(fileBean);
        } else {
            fileBean.setFilename(albumBean.getAlbumname());
            fileBean.setFilepath("/我的相册/" + albumBean.getAlbumname() + "/");
            fileBean.setUploadtime(DateUtil.getCurrentTime());
            fileService.updateFile(fileBean);
        }

        albumService.uploadAlbum(albumBean);

        restResult.setSuccess(true);
        restResult.setData("修改相册成功");
        return JSON.toJSONString(restResult);
    }

    /**
     * 获取用户的所有相册列表
     *
     * @return
     */
    @RequestMapping(value = "/getalbumlist")
    @ResponseBody
    public String getAlbumList() {
        RestResult<List<AlbumBean>> restResult = new RestResult<List<AlbumBean>>();
        UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
        if (sessionUserBean == null) {
            restResult.setSuccess(false);
            restResult.setErrorMessage("用户没有登录");
            return JSON.toJSONString(restResult);
        }

        List<AlbumBean> albumList = albumService.getAlbumListByUser(sessionUserBean);
        restResult.setData(albumList);
        restResult.setSuccess(true);
        return JSON.toJSONString(restResult);
    }

}

